from flask import Flask, render_template, redirect, request, session, url_for
import functools

app = Flask(__name__)

app.secret_key = "1fsdfs2342df"


def auth(func):
    @functools.wraps(func)
    def inner(*args, **kwargs):
        username = session.get("user")
        if not username:
            return redirect(url_for('login'))
        return func(*args, **kwargs)
    return inner


@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == "GET":
        return render_template('login.html')  # render
    user = request.form.get("user")
    pwd = request.form.get("pwd")
    if user == 'changxin' and pwd == '123':
        session["user"] = user
        return redirect('/index')
    error = "用户名或密码错误"
    return render_template('login.html', error=error)


@app.route('/index')
@auth
def index():
    return '首页'


if __name__ == '__main__':
    app.run()
